package com.asiainfo.simpledao;

import java.util.Map;

import javax.sql.DataSource;

public class MySqlDao extends AbstractDao {

	public MySqlDao(DataSource dataSource) {
		super(dataSource);
	}

	public MySqlDao(String url, String user, String password) {
		super(url, user, password);
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Page selectList(String sql, int currPage, int pageSize, Object... params) {
		int count = count(sql, params);
		Page page = new Page();
		page.setCurrPage(currPage);
		page.setPageSize(pageSize);
		page.setTotal(count);
		int startRow = (currPage - 1) * pageSize;
		page.setRows(selectList(getPageSql(sql, startRow < 0 ? 0 : startRow, pageSize), params));
		return page;
	}

	private String getPageSql(String sql, int startRow, int pageSize) {
		if (startRow == 0) {
			return String.format("%s LIMIT %d", sql, pageSize);
		} else {
			return String.format("%s LIMIT %d,%d", sql, startRow, pageSize);
		}
	}

	@Override
	public Page selectList(String sql, int currPage, int pageSize, Map<String, Object> params) {
		int count = count(sql, params);
		Page page = new Page();
		page.setCurrPage(currPage);
		page.setPageSize(pageSize);
		page.setTotal(count);
		int startRow = (currPage - 1) * pageSize;
		page.setRows(selectList(getPageSql(sql, startRow < 0 ? 0 : startRow, pageSize), params));
		return page;
	}

}
